<template>
  <page-header-wrapper>
    <a-card>
      <p class="info">基本信息</p>

      <!-- <a-button type="primary" class="add" @click="addNature">添加</a-button> -->
      <a-form-model
        ref="form"
        :model="basicform"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        v-for="(basicform, i) in form"
        :key="i"
        class="box"
        :hideRequiredMark="true"
      >
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="项目地址：" :label-col="labelCol" :wrapper-col="wrapperCol" prop="projectId">
              <a-select
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                @change="Onchange(basicform.projectId, i)"
                v-model="basicform.projectId"
                style="width:200px"
              >
                <a-select-option :value="item.projectId" v-for="item in repayList" :key="item.projectId">
                  {{ item.addr }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="客户名称：" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-model="clientName[i]" style="width:200px" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row class="left">
          <a-form-model-item label="还款性质：" prop="nature">
            <a-radio-group v-model="basicform.nature" @change="Onchange(basicform.projectId, i)">
              <a-radio :value="item.value" v-for="item in natures" :key="item.text">
                {{ item.text }}
              </a-radio>
            </a-radio-group>
            <a-input style="width:120px" v-model="basicform.otherName" :disabled="basicform.nature != 4" />
          </a-form-model-item>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="金额：" prop="amount">
              <m-input-number v-model="basicform.amount" class="length" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="还款日期：" prop="repayDate">
              <a-date-picker v-model="basicform.repayDate" :disabled-date="disabledDate(i)" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row class="left">
          <a-form-model-item label="银行：" prop="bank">
            <a-radio-group v-model="basicform.bank">
              <a-radio :value="item.value" v-for="item in banks" :key="item.text">
                {{ item.text }}
              </a-radio>
              <a-input style="width:120px" v-model="others[i]" :disabled="basicform.bank != '其他'" />
            </a-radio-group>
          </a-form-model-item>
        </a-row>
        <a-row v-if="basicform.nature == 1">
          <a-col :span="8">
            <a-form-model-item label="税款：" prop="levyIssuer">
              <a-select v-model="basicform.levyIssuer">
                <a-select-option :value="item" v-for="item in levy" :key="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="税款金额" prop="tax">
              <m-input-number :value="tax[i]" class="length" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row class="left">
          <a-form-model-item label="备注：" prop="remarks">
            <a-textarea class="text" v-model="basicform.remarks" :rows="4"></a-textarea>
          </a-form-model-item>
          <a-button class="float-right" v-if="i != 0" type="primary" @click="remove(i)">删除</a-button>
        </a-row>
      </a-form-model>
      <a-button type="primary" style="margin-left:40%" @click="addNature">继续添加</a-button>
      <a-button type="primary" style="margin-left:50px" @click="finish">完成</a-button>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import { natures, banks } from '@/dict'
import { createRepay, getAddr, getList, getRepayState } from '@/api/common'
import moment from 'moment'
import { commonRule, dateRule } from '@/utils/rules'
export default {
  name: 'addRepay',
  data() {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      natures,
      banks,
      other: [''],
      others: [''],
      repayList: [],
      levy: ['Approver issuer levy', 'Non-resident withholding tax', '不适用'],
      clientName: [],
      id: '',
      start: [null],
      end: [null],
      form: [
        {
          projectId: '',
          nature: 1,
          amount: '',
          repayDate: '',
          bank: 'HSBC',
          levyIssuer: 'Approver issuer levy',
          tax: '',
          remarks: '',
          otherName: ''
        }
      ],
      rules: {
        projectId: commonRule,
        nature: commonRule,
        amount: commonRule,
        repayDate: dateRule,
        levyIssuer: commonRule
      },
      pagination: {
        total: 1,
        pageSize: 10,
        onChange: this.getData
      }
    }
  },
  mounted() {
    if (!this.$route.query.id) {
      this.getData()
    }
  },
  computed: {
    tax() {
      return this.form.map(el => {
        if (el.levyIssuer == '不适用') {
          return 0
        } else {
          const a = (el.tax = el.levyIssuer == 'Approver issuer levy' ? (el.amount * 2) / 100 : el.amount / 10)
          return a.toFixed(2)
        }
      })
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    disabledDate(i) {
      const start = this.start[i]
      const end = this.end[i]
      return function(endValue) {
        if (!start || !end) {
          return false
        }
        return start.valueOf() > endValue.valueOf() || end.valueOf() + 24 * 3600 * 1000 < endValue.valueOf()
      }
    },
    async Onchange(v, i) {
      const choose = this.repayList.find(el => el.projectId == v)
      this.clientName[i] = choose.clientName
      const form = {
        page: 1,
        limit: 1,
        projectIds: v
      }
      const resTime = await getList(form)
      const Time = resTime.result.data.list[0]
      const state = await getRepayState({ projectId: v })
      const repayState = state.result.data
      if (this.form[i].nature == 1 && repayState.isFirst == 1) {
        this.$set(this.start, i, Time.firstLoanTime ? moment(Time.firstLoanTime * 1000) : null)
        this.$set(
          this.end,
          i,
          Time.realEndTime ? moment(Time.realEndTime * 1000) : Time.sysEndTime ? moment(Time.sysEndTime * 1000) : null
        )
      } else if (this.form[i].nature == 1 && repayState.isFirst == 0) {
        this.$set(this.start, i, repayState.repayDate ? moment(repayState.repayDate * 1000) : null)
        this.$set(
          this.end,
          i,
          Time.realEndTime ? moment(Time.realEndTime * 1000) : Time.sysEndTime ? moment(Time.sysEndTime * 1000) : null
        )
      } else {
        this.$set(this.start, i, Time.firstLoanTime ? moment(Time.firstLoanTime * 1000) : null)
        this.$set(
          this.end,
          i,
          Time.realEndTime ? moment(Time.realEndTime * 1000) : Time.sysEndTime ? moment(Time.sysEndTime * 1000) : null
        )
      }
    },
    addNature() {
      this.form.push({
        addr: '',
        nature: 1,
        amount: '',
        repayDate: '',
        bank: 'HSBC',
        levyIssuer: 'Approver issuer levy',
        tax: '',
        remarks: '',
        otherName: ''
      })
      this.others.push('')
    },
    remove(i) {
      this.form.splice(i, 1)
      this.clientName.splice(i, 1)
    },
    // contiune() {
    //   const repayDateParse = x =>
    //     Number(
    //       moment(x)
    //         .startOf('day')
    //         .format('X')
    //     )
    //   let _form = {
    //     projectId: this.id,
    //     items: []
    //   }
    //   let valid = false
    //   this.form.forEach((el, i) => {
    //     this.$refs.form?.[i]?.validate(v => (valid = v))
    //     if (!valid) return
    //     let item = Object.assign({}, el)
    //     item.tax = item.nature == 1 ? this.tax[i] : 0
    //     item.repayDate = repayDateParse(el.repayDate)
    //     if (item.bank == '其他') item.bank = this.others[i]
    //     _form.items.push(item)
    //   })
    //   if (this.addr) {
    //     if (valid) {
    //       createRepay(_form)
    //       this.form = [
    //         {
    //           nature: 1,
    //           amount: '',
    //           repayDate: '',
    //           bank: 'HSBC',
    //           levyIssuer: '',
    //           tax: '',
    //           remarks: '',
    //           otherName: ''
    //         }
    //       ]
    //     }
    //   } else {
    //     this.$message.error('请输入项目地址')
    //   }
    // },
    async finish() {
      const repayDateParse = x =>
        Number(
          moment(x)
            .startOf('day')
            .format('X')
        )
      let valid = false
      const _form = []
      this.form.forEach((el, i) => {
        this.$refs.form?.[i]?.validate(v => (valid = v))
        if (!valid) return
        let item = Object.assign({}, el)
        // console.log(this.form)
        item.tax = item.nature == 1 ? item.tax : 0
        item.repayDate = repayDateParse(el.repayDate)
        if (item.bank == '其他') item.bank = this.others[i]
        _form.push(item)
        // el.tax = el.nature == 1 ? this.tax[i] : 0
        // el.repayDate = repayDateParse(el.repayDate)
        // if (el.bank == '其他') el.bank = this.others[i]
      })
      if (valid) {
        const res = await createRepay(_form)

        // console.log(res.result.data)
        if (res.result.data) {
          this.$router.back(-1)
        }
      }
    },
    async getData() {
      const res = await getAddr()
      this.repayList = res.result.data
    }
  }
}
</script>
<style lang="css" scoped>
.info {
  border-left: 2px solid #1890ff;
  padding-left: 10px;
  font-size: 25px;
  margin-left: 50px;
}
.add {
  float: right;
  margin-bottom: 10px;
  margin-right: 20px;
}
.box {
  clear: both;
  border: 1px solid rgb(184, 182, 182);
  padding: 15px;
  margin: 25px;
  border-radius: 10px;
}
.text {
  resize: unset;
  vertical-align: top;
}
.left {
  margin-left: -240px;
}
.length {
  width: 200px;
}
</style>
